﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Caiji.OpCommand
{
    public class Commands:ICommand
    {
        //能否执行 命令
        readonly Func<bool> _canExecute;
        //执行命令的 方法
        readonly Action _execute;
        public Commands(Action execute, Func<bool> canExecute =null)
        {
            _canExecute = canExecute;
            _execute = execute;
        }
        public bool CanExecute(object? parameter)
        {
            if (_canExecute == null) return true;
            return _canExecute();
        }

        public void Execute(object? parameter)
        {
            _execute();
        }
        //只有当提供了 _canExecute 委托时才会注册事件
        //使用 WPF 的 CommandManager.RequerySuggested 机制自动触发命令可用性检查
        public event EventHandler? CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                    CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (_canExecute != null)
                    CommandManager.RequerySuggested -= value;
            }
        }
    }
}
